package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 消息的生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //添加kafka的配置
        Properties properties = new Properties();
        //链接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"121.4.86.29:9092");
        //key和value序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //设置消息发送确认
        properties.put(ProducerConfig.ACKS_CONFIG,"all");

        //重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,"10");

        //数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"lz4");

        //创建消息的生产者
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);

        for (int i = 0; i < 5; i++) {
            //封装消息
            ProducerRecord<String,String> kvProducerRecord = new ProducerRecord<String,String>("kafka-topic","key-077","value-hello kafka");
            //发送消息
            //同步发送消息
            RecordMetadata recordMetadata = producer.send(kvProducerRecord).get();
            System.out.println(recordMetadata.offset());
        }



        //异步发送消息
        /*producer.send(kvProducerRecord, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if(e != null){
                    System.out.println(e);
                }

                System.out.println(recordMetadata.offset());
            }
        });*/
        //关闭消息通道，不然消息发送不成功
        producer.close();
    }
}
